package com.opages.mvc.adapter.nacos.serviceregistry;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.opages.mvc.adapter.common.client.serviceregistry.ServiceRegistry;
import com.opages.mvc.adapter.nacos.model.NacosDiscoveryProperties;
import org.springframework.util.StringUtils;

/**
 * Nacos注册<动词语义>
 * @author daizhong.liu
 *
 */
public class NacosServiceRegistry implements ServiceRegistry<NacosRegistration>  {
    private final NamingService namingService;
    private final NacosDiscoveryProperties nacosDiscoveryProperties;

    public NacosServiceRegistry(NacosDiscoveryProperties nacosDiscoveryProperties) {
        this.nacosDiscoveryProperties = nacosDiscoveryProperties;
        this.namingService = this.nacosDiscoveryProperties.namingServiceInstance();
    }

    @Override
    public void register(NacosRegistration registration) {
        String serviceId = registration.getServiceId();
        if (StringUtils.isEmpty(registration.getServiceId())) {
            throw new RuntimeException("No service to register for nacos client...");
        }
        String group = registration.getNacosDiscoveryProperties().getGroup();
        Instance instance = getNacosInstanceFromRegistration(registration);
        try {
            namingService.registerInstance(serviceId,group,instance);
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deregister(NacosRegistration registration) {
        String serviceId = registration.getServiceId();
        if (StringUtils.isEmpty(registration.getServiceId())) {
            throw new RuntimeException("No service to register for nacos client...");
        }
        String group = registration.getNacosDiscoveryProperties().getGroup();
        try {
            namingService.deregisterInstance(serviceId, group, registration.getHost(),
                    registration.getPort(), nacosDiscoveryProperties.getClusterName());
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Instance getNacosInstanceFromRegistration(NacosRegistration registration) {
        Instance instance = new Instance();
        instance.setIp(registration.getHost());
        instance.setPort(registration.getPort());
        instance.setWeight(registration.getNacosDiscoveryProperties().getWeight());
        instance.setClusterName(registration.getNacosDiscoveryProperties().getClusterName());
        instance.setMetadata(registration.getMetadata());
        return instance;
    }
}
